﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace THO7AlgoritmTimerApplication {
    class contrast_add : VisionAlgorithm {
        float contrasts = 0;
        public contrast_add(String name) : base(name) { }
        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            contrasts = (float)getMarge();
            Bitmap dest = new Bitmap(sourceImage, sourceImage.Width, sourceImage.Height);
            BitmapData bmpdata = sourceImage.LockBits(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            BitmapData bmpdata1 = dest.LockBits(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
            IntPtr ptr = bmpdata.Scan0;
            IntPtr ptr1 = bmpdata1.Scan0;
            int bytes = Math.Abs(bmpdata.Stride) * sourceImage.Height;
            byte[] rgbValues = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            contrasts = (100.0f + contrasts) / 100.0f;
            contrasts *= contrasts;
            for (int counter = 0; counter < rgbValues.Length - 1; counter += 3) {
                byte color = (byte)((rgbValues[counter] + rgbValues[counter + 1] + rgbValues[counter + 2]) / 3);
                rgbValues[counter] = color;
                rgbValues[counter + 1] = color;
                rgbValues[counter + 2] = color;
            }
            for (int counter = 0; counter < rgbValues.Length - 1; counter += 3) {
                float new_contrast = rgbValues[counter] / 255.0f;
                new_contrast = (((new_contrast - 0.5f) * contrasts) + 0.5f) * 255.0f;
                if (new_contrast > 255) {
                    new_contrast = 255;
                } else if (new_contrast < 0) {
                    new_contrast = 0;
                }
                rgbValues[counter] = (byte)new_contrast;
                rgbValues[counter + 1] = (byte)new_contrast;
                rgbValues[counter + 2] = (byte)new_contrast;
            }
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr1, bytes);
            sourceImage.UnlockBits(bmpdata);
            dest.UnlockBits(bmpdata1);
            return dest;
        }
    }
}

